<?php

/**
 * Framework_Module_People_CP
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Modules
 * @filesource
 */


/**
 * Framework_Module_People_CP
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Modules
 */
class Framework_Module_People_CP extends Framework_Module_CP
{
	/**
     * $navParts
     *
     * @access      private
     * @var         array		$navParts      Url parts
     */	
	private $navParts = array();
  
	/**
     * __construct
     *
     * Initializes the module: sets the default presenter, the allowed
     * conrollers, and the allowed events
     *
     * @access 		public
     * @return 		void
     */
	public function __construct()
	{
		parent::__construct();
		$this->navParts = Framework::$request->requestParts;
		$this->tplFile = 'CpPeople.tpl';
		

	}

	/**
     * __default
     *
     * Generates people control panel
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function __default()
	{

		$navigator = new Framework_Navigator('/'.$this->owner->userName.'/People/CP/', 'peopleNavList');
		$navigator->setItem('friendsListItem','friends','friends');
		$navigator->setItem('watchingListItem','watching','watching');
		$navigator->setItem('watchedByListItem','watchedBy','watchedBy');
		
		if (isset($_GET['unwatch']) && preg_match('/^[0-9]+$/', $_GET['unwatch'])) {
				$this->unwatch($_GET['unwatch']);
		}
		 
		if ($this->navParts[0]) {
			if (strcasecmp($this->navParts[0], 'watchedBy') == 0) {
				$this->setData('watchedBy', true);
			}
			
			$navigator->setActive($this->navParts[0].'ListItem');
			
			$result = $this->owner->getPeople($this->navParts[0]);
		} else {
			$navigator->setActive('friendsListItem');
			$result = $this->owner->getPeople('friends');
		}
		
		$this->setData('peopleNavList', $navigator->getNavigation());
	
		
		
		 
		if(!PEAR::isError($result)) {
			$people = $result->getData();
			
			if (count($people)) {
				$this->setData('people', $people);
				$this->setData('pager', $result->getPager());
				$this->setData('sortLinks', $result->getSortLinks());
			} else {
				$this->setData('noResults', 'No People to List');
			}
		} else {
			return $result;
		}

		return true;

	}

	


	/**
     * unwatch
     *
     * takes user id argument, two possible return formats, ajax or normal 
     * also, if domain of owner matches domain of..
     *
     * @access 		private
     * @paran		integer			$id			Siteuser ID to unwatch
     * @return 		boolean 		boolean true
     */
	private function unwatch($id)
	{
			$siteUserTable = Framework_DB::tableFactory('SiteUser');

			$queryArray = array(
				'sqlKey' => array(
					'select' => 'userName, siteDomain',
					'where'  => 'idSiteUser = ?',
					'get' => 'row',
				),
				'params' => array($id)
			);
				
			$siteuser = $siteUserTable->select($queryArray);
			
			if (!PEAR::isError($siteuser)) {
				if ($siteuser['siteDomain'] == Framework::$site->domain) {
					// basic unwatch
					$result = $this->doUnwatch($id, true);
					if (PEAR::isError($result)) {
						$errors[] = 'Database Error: Cannot unwatch';
					} else {
						$this->setData('unwatchConfirm', 'User Unwatched');
					}
				} else {
					// do remote unwatch
					require_once "HTTP/Request.php";
					$req = new HTTP_Request('http://'.$siteuser['siteDomain'].'/'.$siteuser['userName'].'/User/UnwatchRemote');
					$req->setMethod(HTTP_REQUEST_METHOD_POST);

					// Generate Signature
					require_once 'Crypt/RSA.php';
					require_once 'Crypt/RSA/Key.php';
						
					$rsa_obj = new Crypt_RSA(array(
					'private_key' => Crypt_RSA_Key::fromString($this->owner->privateKey),
					));

					$time = time();
						
					$signature = $rsa_obj->createSign($time.$siteuser['userName'].$siteuser['siteDomain']);
					if ($rsa_obj->isError()){
						$error = $rsa_obj->getLastError();
						$errors[] = $error->getMessage();
					}

					$req->addPostData('time',$time);
					$req->addPostData('from',$this->owner->userName.'@'.$this->owner->siteDomain);
					$req->addPostData('signature', $signature);
						
					$result = $req->sendRequest();
					if (PEAR::isError($result)) {
						$errors[] = 'Network Error: Could not contact site to complete request';
						$errors[] = $result->getMessage();
					} else {
						$xml = $req->getResponseBody();
						$xml = @simplexml_load_string($xml);
						if($xml) {
							if ($xml->header->type == 'error'){
								$errors[] = 'Error Unwatching: '.$xml->message->errorMessage;

							} elseif($xml->header->type == 'UnwatchRemote') {
								$result = $this->doUnwatch($id);
								if (PEAR::isError($result)) {
									$errors[] = 'Database Error: Cannot unwatch';
								} else {
									$this->setData('unwatchConfirm', 'User Unwatched');
								}
							} else {
								$errors[] = 'Invalid XML response '.$xml->header->type;
							}
						} else {
							$errors[] = 'SimpleXML: Invalid XML <br>'.$req->getResponseBody();
						}
					}
				}
			} else {
				$errors[] = 'Database Error: Cannot select user';
			}
		

		if ($errors) {
			$this->setData('errors', $errors);
			
		}
		
			
		return true;
	}

	/**
     * doUnwatch
     *
     * Actually do the unwatch
     *
     * @access 		private
     * @param		integer			$idSiteUser			Siteuser ID to unwatch
     * @param		boolean			$localOnly			Is the siteuser local or remote too?
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	private function doUnwatch($idSiteUser, $localOnly = false) {

		$friendStatusTable = Framework_DB::tableFactory('FriendStatus');

		$result = $friendStatusTable->update(array('watchingUser' => 0), array('idOwner' => $this->owner->idOwner, 'idSiteUser' => $idSiteUser));
		 
		if(PEAR::isError($result)) {
			return $result;
		} else {
			if ($localOnly) {
				$siteUserTable = Framework_DB::tableFactory('SiteUser');
				$queryArray = array(
					'sqlKey' => array(
						'select' => 'idOwner',
						'where'  => 'idSiteUser = ?',
						'get'    => 'one'
					),
					'params' => array($idSiteUser)
				);
				$idOwner = $siteUserTable->select($queryArray);
				$result = $friendStatusTable->update(array('watchedByUser' => 0), array('idOwner' =>$idOwner, 'idSiteUser' => $this->owner->idSiteUser));
				if(PEAR::isError($result)) {
					return $result;
				}
			}
			
			return true;
		}
		 
	}

}



?>